<template>
  <div class="ek-select">
    <el-select
      v-model="value"
      filterable
      @blur="blur"
      @focus="focus"
      @change="change"
      @clear="clear"
      :loading="loading"
      loading-text="加载中"
      no-data-text="无数据"
      :placeholder="placeholder"
      :disabled="disabled"
      :clearable="clearable"
      :multiple="multiple"
      :collapse-tags="collapseTags"
      :collapse-tags-tooltip="collapseTagsTooltip"
      :remote="true"
      :remote-method="remoteMethod"
      :size="size"
    >
      <el-option
        v-for="item in ekOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
      <!--        
      <template #header>
        选中列表
      </template> -->
      <template #footer>
        <el-pagination
          size="small"
          layout="prev, pager, next, total"
          v-model:currentPage="pages.currentPage"
          v-model:pageSize="pages.pageSize"
          :total="pages.total"
          @current-change="handleCurrentChange"
        />
      </template>
    </el-select>
  </div>
</template>

<script setup>
import {
  nextTick,
  defineComponent,
  defineEmits,
  onMounted,
  getCurrentInstance,
  computed,
  ref,
  watch,
  reactive,
  defineExpose
} from "vue";
import { getDimensionByCode } from "@/utils/sys.js";

import queryBulider from "@/utils/queryBulider";
const props = defineProps({
  modelValue: {
    type: [String, Number, Array, Boolean],
    default: "",
  },
  // 显示名称
  name: {
    type: [String, Array],
    default: "",
  },
  // 禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  // 是否显示清除
  clearable: {
    type: Boolean,
    default: true,
  },
  // 默认显示
  placeholder: {
    type: String,
    default: "请选择",
  },
  // 维度编码，存在则直接查询维度接口，优先级比url高
  modelCode: {
    type: String,
    default: "",
  },
  // 远程地址,存在远程地址
  url: {
    type: String,
    default: "",
  },
  //选项，选项里面必须包含label和value
  options: {
    type: Array,
    default: () => [],
  },
  // 是否多选
  multiple: {
    type: Boolean,
    default: false,
  },
  // 多选是否折叠
  collapseTags: {
    type: Boolean,
    default: true,
  },
  collapseTagsTooltip: {
    type: Boolean,
    default: true,
  },
  // 字段映射
  mapping: {
    type: Object,
    default: () => ({
      label: ["label"],
      value: "value",
    }),
  },
  size: {
    type: String,
    default: "default",
  },
  // 默认查询条件, 参考queryBulider
  defaultSearchParam: {
    type: Array,
    default: [],
  },
  orders: {
    type: Array,
    default: [
      {
        field: "id",
        sort: "desc",
      },
    ],
  },
});

const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();

const { $http } = globalProperties;

const emit = defineEmits([
  "update:modelValue",
  "blur",
  "focus",
  "change",
  "clear",
]);

const value = computed({
  get() {
    if (props.multiple) {
      return props.modelValue;
    } else {
      return props.modelValue;
    }
  },
  set(value) {
    if (props.multiple) {
      emit("update:modelValue", value);
    } else {
      emit("update:modelValue", value);
    }
  },
});
const url = computed(() => {
  if (props.url || props.modelCode) {
    return props.url || props.modelCode;
  } else {
    return "";
  }
});

// 选项列表
const ekOptions = computed(() => {
  if (url.value) {
    return remoteData.value;
  } else {
    return props.options;
  }
});
// 获取分页数据
let pages = computed(() => {
  return {
    currentPage: 1, // 当前页
    pageSize: 20, // 每页显示条数
    total: 0, // 总条数
    searchParam: props.defaultSearchParam, // 查询条件数据对象
    orders: props.orders
  };
});
// 加载中
let loading = ref(false);
function init() {
  // 存在远程地址，开启初始化获取数据或者存在值
  if (url.value) {
    // 聚焦，开始初始化， 或者存在值且name为空，则直接执行获取数据
    if (
      (!props.multiple && (value.value || value.value === 0) && !props.name) ||
      (props.multiple && value.value?.length && !props.name?.length)
    ) {
    } else {
      if (props.multiple) {
        for (let i = 0; i < value.value.length; i++) {
          remoteData.value.push({
            label: props.name[i],
            value: value.value[i],
          });
        }
      } else {
        remoteData.value.push({
          label: props.name,
          value: value.value,
        });
      }
    }
  }
}
// 获取远程数据
const remoteData = ref([]);
// 获取下拉列表
async function getData(url) {
  // 加载中或者是，已经加载过了直接返回
  if (loading.value) {
    return;
  }
  loading.value = true;
  let list = null;
  let newUrl = props.modelCode
    ? `/business/basis/getModelByModelCode?modelCode=${props.modelCode}`
    : url;
  let searchParam = [];
  if (searchVal.value) {
    for (let i in props.mapping.label) {
      if (i == 0) {
        searchParam.push({
          symbol: "like",
          paramKey: props.mapping.label[i],
          paramValue: searchVal.value,
        });
      }
    }
    searchParam = queryBulider.insertArrayBetween([...searchParam], {
      logic: "or",
      type: "logic",
    });
    if (pages.value.searchParam.length) {
      searchParam = queryBulider.beforeArrayInsert(searchParam, {
        bracket: "(",
        type: "bracket",
      });
      searchParam = queryBulider.afterArrayInsert(searchParam, {
        bracket: ")",
        type: "bracket",
      });
      searchParam.push({ logic: "and", type: "logic" });
      searchParam = searchParam.concat(pages.value.searchParam);
    }
  } else {
    if (pages.value.searchParam.length) {
      searchParam = searchParam.concat(pages.value.searchParam);
    }
  }

  let res = await $http.post(newUrl, {
    ...props.mapping,
    ...{ search: searchParam },
    pageSize: pages.value.pageSize,
    currentPage: pages.value.currentPage,
    orders: pages.value.orders,
  });
  if (res.status === "success") {
    list = res.data.list?.length ? res.data.list : [];
    pages.value.total = res.data.total;
  }

  remoteData.value = list;
  loading.value = false;
}

// 失去焦点
function blur(event) {
  emit("blur", event);
}
// 聚焦
function focus(event) {
  searchVal.value = "";
  getData(url.value);
  emit("focus", event);
}
// 改变事件, 清空会返回undefined
function change(event) {
  emit("change", event);
}
// 清除事件
function clear() {
  searchVal.value = "";
  emit("clear");
}

// 分页页当前页改变
function handleCurrentChange(event) {
  pages.value.currentPage = event;
  getData(url.value);
}
const searchVal = ref("");
// todo 远程搜索
function remoteMethod(val) {
  searchVal.value = val;
  pages.value.currentPage = 1;
  getData(url.value);
}
defineExpose({
  getOptions: () => {
    return ekOptions.value
  },
});
// todo 如果初始化不请求数据如何回显问题

onMounted(() => {
  init();
});
</script>

<style scoped lang="scss"></style>
